// Mandelbrot emits a PNG image of the Mandelbrot fractal.
package main

import (
	"image"
	"image/color"
	"image/png"
	"math/cmplx"
	"os"
)

func main() {
	const (
		width, height   = 1024, 1024
		widthp, heightp = 2048, 2048
	)

	img := image.NewRGBA(image.Rect(0, 0, width, height))
	for py := 0; py < heightp; py++ {
		y := float64(py)/heightp*4 - 2
		for px := 0; px < widthp; px++ {
			x := float64(px)/widthp*4 - 2
			z := complex(x, y)
			// Image point (px, py) represents complex value z
			img.Set(px/2, py/2, solveNewton(z))
		}
	}
	png.Encode(os.Stdout, img)
}

func solveNewton(z complex128) color.Color {
	const iterations = 100
	const contrast = 15

	z0 := z
	for n := uint8(0); n < iterations; n++ {
		z1 := z0 - (cmplx.Pow(z0, 4)-1)/(4*cmplx.Pow(z0, 3))
		if cmplx.Abs(z1-z0) < 0.00000001 {
			return getColor(contrast, n)
		}
		z0 = z1
	}
	return color.Black
}

func getColor(contrast uint8, n uint8) color.RGBA {

	return color.RGBA{
		R: 255,
		G: byte(255 - contrast*n),
		B: 255,
		A: 255,
	}
}
